<?php

namespace lemon\models\traits;

use Yii;

/**
 * 
 */
trait XmlTrait
{
	public function svgToVector($file){
		$physical_path = Yii::$app->params['FILE_PHYSICAL_PATH'];
		$vals = readXml($file);
		$xml = "";
		foreach ($vals as $val){
			$tag = $val['tag'];
			$type = $val['type'];
			if($tag == "SVG" && $type == 'open'){
				$xml .= "<vector xmlns:android=\"http://schemas.android.com/apk/res/android\" android:width=\"108dp\" android:height=\"108dp\" android:viewportWidth=\"1024\" android:viewportHeight=\"1024\">";
			}elseif($tag == "PATH"){
				$attributes = $val['attributes'];
				$d = $attributes['D'];
				$xml .= "<path android:pathData=\"$d\" android:fillColor=\"#FFFFFF\"/>";
			}elseif($tag == "SVG" && $type == 'close'){
				$xml .= "</vector>";
			}
		}
		return $xml;
	}
	
	public function pickSvg($file, $ext){
		$vals = $this->readXml($file);
		if($ext=="svg"){
			$pd = "D";
			$co = "FILL";
		}elseif ($ext=="xml"){
			$pd = "ANDROID:PATHDATA";
			$co = "ANDROID:FILLCOLOR";
		}
		$xml = "";
		$i = 1;
		foreach ($vals as $val){
			$tag = $val['tag'];
			$type = $val['type'];
			if($tag == "PATH"){
				$attributes = $val['attributes'];
				$d = str_replace(',', ' ', $attributes[$pd]);
				if(isset($attributes[$co])){
					$fill = $attributes[$co];
				}else{
					$fill = '#FFFFFF';
				}
				$xml .= "<path d=\"$d\" fill=\"{$fill}\" id=\"p$i\" />";
				$i++;
			}
		}
		return $xml;
	}
	
	private function readXml($file){
		$fh = fopen($file,'r');
		$simple = fread($fh,filesize("$file"));
		fclose($fh);
		
		$p = xml_parser_create();
		xml_parse_into_struct($p, $simple, $vals, $index);
		xml_parser_free($p);
		return $vals;
	}
}